<template>
  <div class="app-container">
    <el-card class="box-card">
      <h3>公司介绍</h3>
      <el-form ref="dataForm" :rules="rules" :model="enterprise" label-width="150px">
        <el-form-item label="公司介绍" prop="info">
          <editor :init="editorInit" v-model="enterprise.info" />
        </el-form-item>
      </el-form>
    </el-card>
    <div class="op-container">
      <el-button v-if="!enterprise.id" type="primary" @click="handleCreate">保存内容</el-button>
      <el-button v-if="enterprise.id" type="primary" @click="handleEdit">更新内容</el-button>
    </div>
  </div>
</template>

<style>
.el-card {
  margin-bottom: 10px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
</style>

<script>
import { editEnterprise, createEnterprise, detailEnterprise } from '@/api/enterprise'
import Editor from '@tinymce/tinymce-vue'
import { createStorage } from '@/api/storage'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'

export default {
  name: 'ContAdd',
  components: { Editor },
  data() {
    return {
      id: '',
      enterprise: {
        info: ''
      },
      rules: {
        info: [
          { required: true, message: '公司介绍不能为空', trigger: 'blur' }
        ]
      },
      editorInit: {
        language: 'zh_CN',
        convert_urls: false,
        content_style: 'img {width:100%;height:auto;} p {font-size: 13px;color: #3AA26A;line-height: 22px;}',
        plugins: ['advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'],
        height: 350,
        toolbar: ['searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample', 'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'],
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          createStorage(formData).then(res => {
            success(res.data.url)
          }).catch(() => {
            failure('上传失败，请重新上传')
          })
        }
      }

    }
  },
  computed: {
    headers() {
      return {
        accessToken: getToken()
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init: function() {
      detailEnterprise().then(response => {
        this.enterprise = Object.assign({}, response.data.data)
      })
    },
    handleCreate: function() {
      this.formValidate(1)
    },
    handleEdit: function() {
      this.formValidate(2)
    },
    formValidate: function(type) {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const finalCont = {
            ...this.enterprise
          }
          if (type === 1) {
            createEnterprise(finalCont)
              .then(response => {
                this.$notify.success({
                  title: '成功',
                  message: '添加成功'
                })
              })
              .catch(response => {
                MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
                  confirmButtonText: '确定',
                  type: 'error'
                })
              })
          } else if (type === 2) {
            editEnterprise(finalCont)
              .then(response => {
                this.$notify.success({
                  title: '成功',
                  message: '添加成功'
                })
              })
              .catch(response => {
                MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
                  confirmButtonText: '确定',
                  type: 'error'
                })
              })
          }
        } else {
          this.$notify.error({
            title: '失败',
            message: '请完善以上表单'
          })
        }
      })
    }

  }
}
</script>
